 <template>
  <div class="stories-container">
    <!-- 页面头部 -->
    <div class="stories-header">
      <div class="header-content">
        <h1 class="header-title">传承故事</h1>
        <p class="header-subtitle">聆听非遗传承人的故事，感受传统文化的魅力</p>
      </div>
    </div>

    <!-- 故事分类 -->
    <div class="stories-categories">
      <el-radio-group v-model="selectedCategory" @change="handleCategoryChange">
        <el-radio-button label="all">全部故事</el-radio-button>
        <el-radio-button label="craft">传统技艺</el-radio-button>
        <el-radio-button label="art">传统美术</el-radio-button>
        <el-radio-button label="music">传统音乐</el-radio-button>
        <el-radio-button label="dance">传统舞蹈</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 故事列表 -->
    <div class="stories-content">
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>

      <template v-else>
        <div v-if="filteredStories.length === 0" class="empty-state">
          <el-empty description="暂无相关故事" />
        </div>

        <div v-else class="stories-grid">
          <el-card
            v-for="story in filteredStories"
            :key="story.id"
            class="story-card"
            shadow="hover"
            @click="showStoryDetail(story)"
          >
            <div class="story-image">
              <el-image :src="story.image" fit="contain" />
              <div class="story-category">
                <el-tag :type="getCategoryType(story.category)" effect="dark">
                  {{ story.category }}
                </el-tag>
              </div>
            </div>
            <div class="story-content">
              <h3 class="story-title">{{ story.title }}</h3>
              <p class="story-description">{{ story.description }}</p>
              <div class="story-meta">
                <div class="story-author">
                  <el-avatar 
                    :size="24" 
                    :src="story.author.avatar || defaultUserAvatar" 
                    @error="() => true"
                  />
                  <span>{{ story.author.name }}</span>
                </div>
                <div class="story-actions">
                  <el-button 
                    type="text" 
                    :class="{ 'is-favorite': isFavorite(story.id) }"
                    @click.stop="toggleFavorite(story)"
                  >
                    <el-icon><Star /></el-icon>
                    {{ isFavorite(story.id) ? '已收藏' : '收藏' }}
                  </el-button>
                  <el-button type="text" @click.stop="viewDetail(story.id)">
                    <el-icon><View /></el-icon>
                    查看详情
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </template>
    </div>

    <!-- 故事详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      :title="selectedStory?.title"
      width="50%"
      class="story-detail-dialog"
      :modal-class="'story-detail-modal'"
      :close-on-click-modal="false"
      center
      align-center
      :style="dialogStyle"
    >
      <template #default>
        <div v-if="selectedStory" class="story-detail-wrapper">
          <div class="story-detail">
            <div class="detail-header">
              <div class="detail-image-container">
                <el-image :src="selectedStory.image" fit="cover" class="detail-image" />
              </div>
              <div class="detail-info">
                <div class="detail-meta">
                  <el-tag :type="getCategoryType(selectedStory.category)">
                    {{ selectedStory.category }}
                  </el-tag>
                  <span class="detail-date">{{ selectedStory.date }}</span>
                </div>
                <div class="detail-author">
                  <el-avatar 
                    :size="40" 
                    :src="findMasterAvatar(selectedStory.author.id) || defaultUserAvatar" 
                    @error="() => true"
                  />
                  <div class="author-info">
                    <h4>{{ selectedStory.author.name }}</h4>
                    <p>{{ selectedStory.author.title }}</p>
                  </div>
                </div>
              </div>
            </div>

            <div class="detail-content">
              <div class="content-section">
                <h3>故事简介</h3>
                <p>{{ selectedStory.description }}</p>
              </div>

              <div class="content-section">
                <h3>传承历程</h3>
                <el-timeline>
                  <el-timeline-item
                    v-for="(milestone, index) in selectedStory.milestones"
                    :key="index"
                    :timestamp="milestone.date"
                    placement="top"
                  >
                    <h4>{{ milestone.title }}</h4>
                    <p>{{ milestone.content }}</p>
                  </el-timeline-item>
                </el-timeline>
              </div>

              <div class="content-section">
                <h3>传承感悟</h3>
                <p>{{ selectedStory.insights }}</p>
              </div>

              <div class="content-section">
                <h3>相关图片</h3>
                <el-carousel :interval="4000" type="card" height="300px">
                  <el-carousel-item v-for="(image, index) in selectedStory.gallery" :key="index">
                    <el-image :src="image.url" fit="cover" />
                    <div class="carousel-caption">{{ image.caption }}</div>
                  </el-carousel-item>
                </el-carousel>
              </div>
            </div>

            <div class="detail-footer">
              <div class="interaction-buttons">
                <el-button 
                  :type="isFavorite(selectedStory.id) ? 'warning' : 'primary'" 
                  :icon="Star" 
                  @click="toggleFavorite(selectedStory)"
                >
                  {{ isFavorite(selectedStory.id) ? '取消收藏' : '收藏故事' }}
                </el-button>
                <el-button :icon="Share" @click="handleShare">
                  分享故事
                </el-button>
              </div>
              <div class="story-tags">
                <el-tag
                  v-for="tag in selectedStory.tags"
                  :key="tag"
                  class="mx-1"
                  effect="plain"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { View, Star, Share } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useFavoritesStore } from '@/stores/favoritesStore';
import { useAuthStore } from '@/stores/authStore';
import defaultUserAvatar from '@/assets/images/default_user_avatar.jpg';
import paperCuttingGallery1 from '@/assets/images/stories/paper-cutting/gallery-1.jpg';
import paperCuttingGallery2 from '@/assets/images/stories/paper-cutting/gallery-2.jpg';
import paperCuttingGallery3 from '@/assets/images/stories/paper-cutting/gallery-3.jpg';
import ceramicsGallery1 from '@/assets/images/stories/ceramics/gallery-1.jpg';
import ceramicsGallery2 from '@/assets/images/stories/ceramics/gallery-2.jpg';
import ceramicsGallery3 from '@/assets/images/stories/ceramics/gallery-3.jpg';

const router = useRouter();
const favoritesStore = useFavoritesStore();
const authStore = useAuthStore();

// 状态管理
const selectedCategory = ref('all');
const currentPage = ref(1);
const pageSize = ref(12);
const loading = ref(false);
const detailVisible = ref(false);
const selectedStory = ref(null);

const findMasterAvatar = (masterId) => {
  const master = masters.value.find(m => m.id === masterId);
  return master ? master.avatar : null;
};
const dialogStyle = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  margin: '0 auto'
};

// 故事数据
const stories = ref([
  {
    id: 1,
    title: '剪纸艺术的传承之路',
    description: '从学徒到大师，一位剪纸艺术传承人的成长历程',
    image: paperCuttingGallery3,
    category: '传统美术',
    date: '2024-01-15',
    views: 1234,
    likes: 88,
    author: {
      name: '张大师',
      title: '国家级非遗传承人',
      avatar: defaultUserAvatar
    },
    milestones: [
      {
        date: '1980年',
        title: '拜师学艺',
        content: '开始跟随师父学习剪纸技艺'
      },
      {
        date: '1995年',
        title: '独立创作',
        content: '开始独立创作剪纸作品'
      },
      {
        date: '2010年',
        title: '获得认可',
        content: '被评为国家级非遗传承人'
      }
    ],
    insights: '剪纸艺术不仅是一种技艺，更是一种文化的传承。每一刀每一剪，都承载着对传统文化的热爱与坚守。',
    gallery: [
      {
        url: paperCuttingGallery1,
        caption: '早期作品：喜鹊登梅'
      },
      {
        url: paperCuttingGallery2,
        caption: '获奖作品：百鸟朝凤'
      },
      {
        url: paperCuttingGallery3,
        caption: '最新作品：龙凤呈祥'
      }
    ],
    tags: ['剪纸艺术', '传统美术', '非遗传承']
  },
  {
    id: 2,
    title: '陶瓷工艺的现代传承',
    description: '传统陶瓷工艺与现代设计的完美融合',
    image: ceramicsGallery3,
    category: '传统技艺',
    date: '2024-01-20',
    views: 856,
    likes: 65,
    author: {
      name: '李师傅',
      title: '省级非遗传承人',
      avatar: defaultUserAvatar
    },
    milestones: [
      {
        date: '1990年',
        title: '开始学艺',
        content: '进入陶瓷厂学习传统工艺'
      },
      {
        date: '2005年',
        title: '创新突破',
        content: '开始尝试现代设计元素'
      },
      {
        date: '2020年',
        title: '获得认可',
        content: '作品获得国际设计大奖'
      }
    ],
    insights: '传统工艺需要与时俱进，在保持传统精髓的同时，也要勇于创新，让古老的技艺焕发新的生机。',
    gallery: [
      {
        url: ceramicsGallery1,
        caption: '传统青花瓷作品'
      },
      {
        url: ceramicsGallery2,
        caption: '现代创新设计'
      },
      {
        url: ceramicsGallery3,
        caption: '获奖作品展示'
      }
    ],
    tags: ['陶瓷工艺', '传统技艺', '创新设计']
  }
]);

// 计算属性
const filteredStories = computed(() => {
  if (selectedCategory.value === 'all') {
    return stories.value;
  }
  return stories.value.filter(story => story.category === selectedCategory.value);
});

const total = computed(() => filteredStories.value.length);

// 方法
const handleCategoryChange = () => {
  currentPage.value = 1;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const showStoryDetail = (story) => {
  selectedStory.value = story;
  detailVisible.value = true;
};

const getCategoryType = (category) => {
  const types = {
    '传统技艺': 'success',
    '传统美术': 'warning',
    '传统音乐': 'info',
    '传统舞蹈': 'danger'
  };
  return types[category] || '';
};

const handleLike = async () => {
  if (!selectedStory.value) return;
  
  try {
    await toggleFavorite(selectedStory.value);
  } catch (error) {
    ElMessage.error(error.message || '操作失败');
  }
};

const handleShare = () => {
  ElMessage.success('分享功能开发中...');
};

// 检查是否已收藏
const isFavorite = (storyId) => {
  return favoritesStore.isFavorite(storyId);
};

// 切换收藏状态
const toggleFavorite = async (story) => {
  try {
    if (!authStore.isAuthenticated) {
      ElMessage.warning('请先登录后再收藏');
      router.push('/login');
      return;
    }

    const isCurrentlyFavorite = isFavorite(story.id);
    if (isCurrentlyFavorite) {
      await favoritesStore.removeFavorite(story.id);
      ElMessage.success('已取消收藏');
    } else {
      await favoritesStore.addFavorite({
        id: story.id,
        title: story.title,
        description: story.description,
        coverImage: story.image,
        category: story.category,
        authorName: story.author.name,
        type: 'story'  // 标记为故事类型
      });
      ElMessage.success('收藏成功');
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败');
  }
};

// 查看详情
const viewDetail = (storyId) => {
  router.push(`/story/${storyId}`);
};
</script>

<style scoped>
.stories-container {
  @apply min-h-screen bg-gray-50;
}

/* 页面头部 */
.stories-header {
  @apply bg-primary-600 text-white py-16 px-4;
}

.header-content {
  @apply max-w-4xl mx-auto text-center;
}

.header-title {
  @apply text-4xl font-bold mb-4;
}

.header-subtitle {
  @apply text-xl text-white/80;
}

/* 故事分类 */
.stories-categories {
  @apply bg-white shadow-sm p-4 flex justify-center;
}

/* 故事列表 */
.stories-content {
  @apply max-w-7xl mx-auto p-6;
}

.loading-state {
  @apply p-8;
}

.empty-state {
  @apply py-12;
}

.stories-grid {
  @apply grid grid-cols-1 lg:grid-cols-2 gap-16;
}

.story-card {
  @apply transition-all duration-300 hover:shadow-lg;
  max-width: 100%;
}

.story-image {
  @apply overflow-hidden;
  height: 400px;
  width: 450px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  margin-bottom: 16px;
  position: relative;
}

.story-image .el-image {
  @apply w-full h-full;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  margin: auto;
}

.story-image :deep(img) {
  @apply object-contain w-full h-full;
  margin: auto;
}

.story-category {
  @apply z-10;
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
}

.story-content {
  @apply p-6;
}

.story-title {
  @apply text-2xl font-semibold text-gray-800 mb-4;
}

.story-description {
  @apply text-lg text-gray-600 mb-6 line-clamp-3;
}

.story-meta {
  @apply flex justify-between items-center pt-4;
}

.story-author {
  @apply flex items-center gap-4;
}

.story-author :deep(.el-avatar) {
  width: 48px !important;
  height: 48px !important;
}

.story-author span {
  @apply text-base;
}

.story-actions {
  @apply flex gap-2;
}

.story-actions .el-button {
  @apply px-0;
}

.story-actions .el-icon {
  @apply mr-2;
}

.is-favorite {
  @apply text-primary-500;
}

.el-button [class*='el-icon'] + span {
  @apply ml-2;
}

/* 分页 */
.pagination-section {
  @apply flex justify-center py-6;
}

/* 故事详情弹窗样式 */
:deep(.story-detail-dialog) {
  @apply max-h-[90vh];
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

:deep(.story-detail-dialog .el-dialog) {
  margin: 0 !important;
}

:deep(.story-detail-dialog .el-dialog__body) {
  height: calc(85vh - 120px);
  overflow-y: auto !important;
  padding: 20px !important;
}

.story-detail-wrapper {
  height: 100%;
  overflow-y: auto;
}

.story-detail {
  @apply py-4;
}

/* 图片容器和图片样式 */
.detail-image-container {
  @apply w-1/2 flex justify-center items-start;
  min-width: 400px;
}

.detail-image {
  @apply rounded-lg;
  width: 120px !important;
  height: 90px !important;
}

/* 调整内容间距和布局 */
.detail-header {
  @apply flex flex-col md:flex-row gap-6 mb-6 items-start justify-start w-full;
}

.detail-info {
  @apply flex-1 min-w-0 mt-2;
}

/* 内容区域样式 */
.content-section {
  @apply mb-8;
}

.content-section:last-child {
  @apply mb-4;
}

.content-section h3 {
  @apply text-xl font-semibold text-gray-800 mb-4;
}

/* 轮播图片容器样式调整 */
:deep(.el-carousel__container) {
  @apply max-h-[700px];
}

:deep(.el-carousel__item) {
  @apply overflow-hidden;
  padding: 40px;
}

:deep(.el-carousel__item img) {
  @apply w-full h-full object-contain rounded-lg;
  transform: none;
}

/* 底部操作区样式 */
.detail-footer {
  @apply bg-white border-t mt-8 pt-4;
  margin: 0 -20px;
  padding: 20px;
}

.interaction-buttons {
  @apply flex gap-4;
}

.story-tags {
  @apply flex flex-wrap gap-2;
}

/* Element Plus 样式覆盖 */
:deep(.el-radio-button__inner) {
  @apply px-6;
}

:deep(.el-timeline-item__node) {
  @apply bg-primary-500;
}

:deep(.el-timeline-item__tail) {
  @apply border-l-primary-200;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .story-card {
    max-width: 800px;
  }

  .story-image {
    height: 450px;
  }
}

@media (max-width: 768px) {
  .story-card {
    max-width: 600px;
  }

  .story-image {
    height: 350px;
  }

  .detail-image-container {
    @apply w-full flex justify-center;
    min-width: auto;
  }

  .detail-image {
    width: 400px !important;
    height: 300px !important;
    margin: 0 auto;
  }

  .story-content {
    @apply p-6;
  }
}

@media (max-width: 640px) {
  .story-card {
    max-width: 100%;
  }

  .story-image {
    height: 280px;
  }

  .story-image .el-image {
    transform: scale(0.5);
  }

  .story-content {
    @apply p-4;
  }

  .story-title {
    @apply text-xl;
  }

  .story-description {
    @apply text-base;
  }
}
</style>